package com.hjk.common.interceptor;

import cn.hutool.core.thread.threadlocal.NamedThreadLocal;
import com.hjk.common.utils.concurrency.RuntimeUtils;
import com.hjk.common.utils.date.DateUtils;
import com.hjk.common.utils.date.MyDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");

    public LogInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (log.isDebugEnabled()) {
            long beginTime = System.currentTimeMillis();
            startTimeThreadLocal.set(beginTime);
            log.debug("开始计时: {}  URI: {}", (new SimpleDateFormat("hh:mm:ss.SSS")).format(beginTime), request.getRequestURI());
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            log.info("ViewName: " + modelAndView.getViewName());
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        if (log.isDebugEnabled()) {
            long beginTime = (Long) startTimeThreadLocal.get();
            long endTime = System.currentTimeMillis();
            log.debug("计时结束：{}  耗时：{}  URI: {}  最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",
                    MyDateTimeUtils.formatDefaultDate(),
                    (endTime - beginTime) / 1000.0,
                    request.getRequestURI(),
                    RuntimeUtils.getMaxMemory(),
                    RuntimeUtils.getTotalMemory(),
                    RuntimeUtils.getFreeMemory(),
                    ( RuntimeUtils.getMaxMemory() -  RuntimeUtils.getTotalMemory() + RuntimeUtils.getFreeMemory()) / 1024L / 1024L);
        }

    }
}
